package cn.bluemobi.dylan.step.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.widget.Button;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.bluemobi.dylan.step.R;
import cn.bluemobi.dylan.step.step.UpdateUiCallBack;
import cn.bluemobi.dylan.step.step.bean.RuninngData;
import cn.bluemobi.dylan.step.step.bean.StepData;
import cn.bluemobi.dylan.step.step.bean.Weight;
import cn.bluemobi.dylan.step.step.service.RuningService;
import cn.bluemobi.dylan.step.step.utils.DbUtils;


public class Paobu extends AppCompatActivity implements View.OnClickListener {

    private TextView textView_step;
    private TextView kll2;
    private TextView sd2;
    private TextView textView;
    private Button start;
    private Button close;
    private int step;
    private int step2=0;
    private ImageView iv_left;
    private boolean isBind = false;
    private int seconds = 0;
    private double sum = 0;
    private int time = 0;
    private int step3=0;
    public static int  count = 0;
    private RuningService runingService = null;
    private float newWeight;
    private Handler handler = new Handler();
    /**
     * 当前的日期
     */
    private static String CURRENT_DATE = "";
    ServiceConnection conn = new ServiceConnection(){
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            runingService = ((RuningService.StepBinder) service).getService();
            step = runingService.getStepCount();
            textView_step.setText(String.valueOf(step));
            String time = showTime(seconds);
            textView.setText(time);
            runingService.registerCallback(new UpdateUiCallBack() {
                @Override
                public void updateUi(int stepCount) {
                    step = runingService.CURRENT_STEP;
                    textView_step.setText(String.valueOf(step));
                }
            });
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paobu);
        iv_left = (ImageView) findViewById(R.id.iv_left);
        iv_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Paobu.this,MainActivity.class));
            }
        });
        textView_step=(TextView) findViewById(R.id.tv_step);
        textView = findViewById(R.id.timeView);
        kll2=(TextView) findViewById(R.id.kll2);
        sd2=(TextView) findViewById(R.id.sd2);
        start=(Button) findViewById(R.id.start);
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                runingService.threadDisable = false;
            }
        });
        close = (Button) findViewById(R.id.close);
        close.setOnClickListener(this);
        runTime();
        setupService();
    }
    /**
     * 开启计步服务
     */
    private void setupService() {
        final  Intent intent = new Intent(this,RuningService.class);
        isBind = bindService(intent, conn, Context.BIND_AUTO_CREATE);
        startService(intent);
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
                unbindService(conn);
                isBind = false;
                runingService.threadDisable = true;
                handler.removeCallbacks(mRunnable);
                count = 0;
                stopService(intent);
                startActivity(new Intent(Paobu.this,RunningHistory.class));
                finish();
            }
        });
        List<Weight> weights = new ArrayList<>();

        weights = DbUtils.getQueryLimit7(Weight.class,"id");
        if(weights.size()==0){
            newWeight = 60;
        }else {
            newWeight = Float.valueOf(weights.get(0).getWeight()).floatValue();
        }
    }
    /**
     * 获取当天日期
     *
     * @return
     */
    private String getTodayDate() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }
    public void save(){
        int tempStep = step;
        CURRENT_DATE = getTodayDate();
        RuninngData runinngData = new RuninngData();
        runinngData.setToday(CURRENT_DATE);
        runinngData.setKlc(String.format("%.2f",sum));
        runinngData.setRuningTime(showTime(count));
        runinngData.setTotal(String.format("%.2f",step*0.7/1000));
        DbUtils.insert(runinngData);
    }
    public void onClickStop(View button){
        runingService.threadDisable = true;
    }

    /**
     * 注意 ui线程不能被堵塞，因此不能在ui线程中调用sleep方法
     * 只允许ui线程更新界面，不能在后台线程更新界面
     *
     * ** 使用ui线程的Handler定时更新 **
     * 将任务封装到 Runnable的run方法中 ，通过Handler的
     * post(立即提交任务)或postDelayed(实现定时调度)方法提交到ui线程
     */
    private final Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            int x=seconds-time;
            if(x>=1){
                time=seconds;
                step3=step-step2;
                step2=step;
                String vt=String.format("%.2f",step3*0.7*3.6);
                sd2.setText(vt+"km/h");
                sum=sum+step3*0.7*1.036/1000*newWeight;
                String klc = String.format("%.2f",sum);
                kll2.setText(klc+"klc");//体重=70kg
                //卡路里计算公式：体重（kg）* 距离（km）* 运动系数（k） 跑步：k=1.036
            }
            else{time=seconds;}
            //sd2.setText(step+"m/s")
            String time = showTime(seconds);
            textView.setText(time);
            seconds = count;
//            if(!runingService.threadDisable)
//                count++;
            //sd2.setText(step2*0.5/seconds+"m/s");
            handler.postDelayed(this,100);
        }
    };
    private void runTime(){
        handler.post(mRunnable);

    }
    private  String showTime(int t){
        int hour = (t/3600)%60;
        int minute = (t/60)%60;
        int s = t%60;
        return String.format("%02d:%02d:%02d",hour,minute,s);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(isBind)
        unbindService(conn);//将service与activity解绑
        handler.removeCallbacks(mRunnable);
        Log.i("服务正在运行","return");
    }

    @Override
    public void onClick(View v) {

    }
}